package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {

        //  1. 调用微信接口，获取openid
        String openId = getOpenIdFromWechat(userLoginDTO.getCode());
        log.info("【微信登录】获取到的openid：{}",openId);


        // 2. 将openid存储到数据库
        User user = userMapper.selectByOpenId(openId);
        if (user == null) {
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }


        Map<String,Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID,user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);

        // 3. 生成token
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(openId);
        userLoginVO.setToken(jwt);

        return userLoginVO;
    }

    /**
     * 通过微信服务器获取openid
     * @param code
     * @return
//     */

//    String url = "https://api.wei4c4&secret=7c09e10zation_code&js_code="+code;

    private String getOpenIdFromWechat(String code) {
        Map<String, String> map = new ManagedMap<>();
        map.put("js_code",code);
        map.put("appid","wx778e9f8c1fe0f4c4");
        map.put("secret","7c09e10ae84f65ce23d40de0eaadac8d");
        map.put("grant_type","authorization_code");
        String res = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);
        JSONObject jsonObject = JSON.parseObject(res);
        return jsonObject.get("openid").toString();
    }
}
